<template>
  <el-dialog title="上传供应商" width="33.125rem" :visible.sync="Dialog" :show-close="!Loading" @open="dialogOpen"
    @closed="dialogDlosed" v-dialogDrag append-to-body>

    <el-alert title="导入注意" type="warning" show-icon>
      <div style="display: flex;">
        单元格颜色为: <div style=" background-color: red;
    width: 50px;
    height: 20px;opacity:0.5;"></div> 数据填写错误


      </div>

    </el-alert>
    <el-form v-loading="Loading" ref="Form" :rules="Rules" :model="Form" label-width="6.25rem" class="demo-ruleForm">
      <div class="d-flex">


        <el-form-item label="业务文件：" prop="file">
          <el-upload v-model="Form.file" ref="file" :on-change="uploadFile" :before-remove="deleteFile" action="#"
            :limit="2" :file-list="Form.file" :accept="$Data.Shop_Upload.accept" :auto-upload="false">
            <el-button size="small" type="primary" plain>{{ Form.file.length == 0 ? '点击选择文件' : '重新选择文件' }}</el-button>
          </el-upload>
        </el-form-item>
      </div>
      <fieldset v-if="!$IsNull(Form.success)" class="upload-success">
        <legend>上传业务列表</legend>
        <template v-for="(item, value) in Form.success">
          <span :key="value">{{ item }}</span>
        </template>
      </fieldset>
    </el-form>
    <div slot="footer">
      <el-button size="mini" type="info" :disabled="Loading" @click="Dialog = false" plain>取消</el-button>
      <el-button size="mini" type="success" @click="download" plain>下载文件模板</el-button>
      <el-button size="mini" type="success" :disabled="Loading" @click="upload">确认上传</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapState } from "vuex";

export default {
  data() {
    return {
      // dialog
      Dialog: false,
      // loading
      Loading: false,
      // 表单
      Form: {
        file: [],
        success: [],
      },
      // 规则
      Rules: {
        file: [
          {
            required: true,
            message: "文件不能为空",
            trigger: "change",
          },
        ],
      },
    };
  },
  computed: {
    ...mapState(["User_Info", "User_List"]),
  },
  methods: {
    // dialog 打开的回调
    dialogOpen() {
      this.Form.userId = this.User_Info.id;
    },
    // dialog 关闭动画结束时的回调
    dialogDlosed() {
      var newArr = ["Form"];
      newArr.forEach((item) => {
        this[item] = this.$options.data()[item];
      });
      this.$nextTick(() => {
        this.$refs.Form.resetFields();
      });
    },
    // 上传合同文件
    uploadFile(item) {
      this.Form.file = [item.raw];
    },
    // 删除合同文件
    deleteFile() {
      setTimeout(() => {
        this.Form.file = [];
      }, 400);
    },
    // 下载文件
    async download() {
      this.$Util.$emit("setLoading", true);
      const res = await this.$api.exportSpSupplierTemplate(
        this.List_QueryInfo,
        this.$Data.ExportHeader
      );
      setTimeout(() => {
        this.$Util.$emit("setLoading", false);
        if (res.status != 200) return this.$Message(null, "导出失败", "error");
        this.$Util.$emit("ExportFileReader", {
          res: res.data,
          type: "xls",
          title: "供应商模板",
        });
      }, this.$Data.Submit_Time);
    },
    // 上传业务
    upload() {
      this.$refs.Form.validate(async (valid) => {
        if (!valid) return;
        this.Loading = true;
        var formData = new FormData($(".demo-ruleForm")[0]);
        // formData.set("userId", this.Form.userId);

        this.$refs.file.fileList.forEach((item, value) => {
          if (value === 0) formData.set("file", item);
          else formData.append("file", item);
        });

        const res = await this.$api.importSpSupplier(formData, {
          ...this.$Data.UploadHeader,
          responseType: "blob", // 设置接受类型
        });
        setTimeout(() => {
          this.Loading = false;
          this.Form.file = [];
          if (res.status == 201) {
            var reader = new FileReader();
            reader.readAsDataURL(res.data);
            reader.onload = (e) => {
              var a = document.createElement("a");
              var fileName = formData.get("file").name;
              var str = "---上传失败的";
              var label = fileName.replace(`.${fileName.split(".").pop()}`, "");
              // a.download = label.split(str)[0] + str + '.xlsx'
              a.download = label + str + ".xls";
              a.href = e.target.result;
              a.click();
            };
            this.$Message(null, "有部分无法正常导入，请查看文件", "warning");
            this.$emit("getPage");
            this.Form.success.push(formData.get("file").name);
          } else if (res.status == 200) {
            let reader = new FileReader();
            reader.readAsText(res.data);
            reader.onload = () => {
              var newRes = JSON.parse(reader.result);
              if (newRes.code != 0)
                return this.$Message(newRes.msg, "上传失败", "error");
              this.$Message(null, "上传成功", "success");
              this.$emit("getPage");
              this.Form.success.push(formData.get("file").name);
            };
          }
        }, this.$Data.Submit_Time);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/css/profession/shop/add-shop.scss";
</style>
